<!-- HTTP请求拦截器演示页面 -->
<template>
  <div class="http-interceptor-demo">
    <!-- 统一导航栏组件 -->
    <AppHeader />

    <!-- 主要内容区域 -->
    <main class="demo-container">
      <div class="demo-card">
        <!-- 页面标题 -->
        <h1 class="demo-title">HTTP请求拦截器演示</h1>
        <p class="demo-description">
          展示HTTP请求拦截器的功能，包括请求拦截、响应拦截、错误处理、重试机制等
        </p>

        <!-- 功能演示区域 -->
        <div class="demo-sections">
          <!-- 基础请求演示 -->
          <section class="demo-section">
            <h2 class="section-title">基础请求演示</h2>
            <div class="demo-buttons">
              <el-button 
                type="primary" 
                @click="testGetRequest"
                :loading="loadingStates.get"
              >
                GET请求测试
              </el-button>
              <el-button 
                type="success" 
                @click="testPostRequest"
                :loading="loadingStates.post"
              >
                POST请求测试
              </el-button>
              <el-button 
                type="warning" 
                @click="testPutRequest"
                :loading="loadingStates.put"
              >
                PUT请求测试
              </el-button>
              <el-button 
                type="danger" 
                @click="testDeleteRequest"
                :loading="loadingStates.delete"
              >
                DELETE请求测试
              </el-button>
            </div>
          </section>

          <!-- 错误处理演示 -->
          <section class="demo-section">
            <h2 class="section-title">错误处理演示</h2>
            <div class="demo-buttons">
              <el-button 
                type="info" 
                @click="testNetworkError"
                :loading="loadingStates.networkError"
              >
                网络错误测试
              </el-button>
              <el-button 
                type="warning" 
                @click="testAuthError"
                :loading="loadingStates.authError"
              >
                认证错误测试
              </el-button>
              <el-button 
                type="danger" 
                @click="testServerError"
                :loading="loadingStates.serverError"
              >
                服务器错误测试
              </el-button>
            </div>
          </section>

          <!-- 重试机制演示 -->
          <section class="demo-section">
            <h2 class="section-title">重试机制演示</h2>
            <div class="demo-buttons">
              <el-button 
                type="primary" 
                @click="testRetryMechanism"
                :loading="loadingStates.retry"
              >
                重试机制测试
              </el-button>
              <el-button 
                type="success" 
                @click="testTimeoutRequest"
                :loading="loadingStates.timeout"
              >
                超时请求测试
              </el-button>
            </div>
          </section>

          <!-- 请求配置演示 -->
          <section class="demo-section">
            <h2 class="section-title">请求配置演示</h2>
            <div class="demo-form">
              <el-form :model="requestConfig" label-width="120px">
                <el-form-item label="请求URL">
                  <el-input v-model="requestConfig.url" placeholder="请输入请求URL" />
                </el-form-item>
                <el-form-item label="请求方法">
                  <el-select v-model="requestConfig.method" placeholder="选择请求方法">
                    <el-option label="GET" value="GET" />
                    <el-option label="POST" value="POST" />
                    <el-option label="PUT" value="PUT" />
                    <el-option label="DELETE" value="DELETE" />
                    <el-option label="PATCH" value="PATCH" />
                  </el-select>
                </el-form-item>
                <el-form-item label="请求数据">
                  <el-input 
                    v-model="requestConfig.data" 
                    type="textarea" 
                    :rows="3"
                    placeholder="请输入JSON格式的请求数据"
                  />
                </el-form-item>
                <el-form-item label="显示加载">
                  <el-switch v-model="requestConfig.showLoading" />
                </el-form-item>
                <el-form-item label="显示错误">
                  <el-switch v-model="requestConfig.showError" />
                </el-form-item>
                <el-form-item label="重试次数">
                  <el-input-number 
                    v-model="requestConfig.retryCount" 
                    :min="0" 
                    :max="5"
                    placeholder="重试次数"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button 
                    type="primary" 
                    @click="testCustomRequest"
                    :loading="loadingStates.custom"
                  >
                    发送自定义请求
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </section>
        </div>

        <!-- 响应结果展示 -->
        <section class="demo-section">
          <h2 class="section-title">响应结果</h2>
          <div class="response-display">
            <el-tabs v-model="activeTab" type="border-card">
              <el-tab-pane label="响应数据" name="response">
                <pre class="response-content">{{ responseData }}</pre>
              </el-tab-pane>
              <el-tab-pane label="错误信息" name="error">
                <pre class="error-content">{{ errorData }}</pre>
              </el-tab-pane>
              <el-tab-pane label="请求日志" name="log">
                <div class="log-content">
                  <div 
                    v-for="(log, index) in requestLogs" 
                    :key="index"
                    class="log-item"
                    :class="log.type"
                  >
                    <span class="log-time">{{ log.time }}</span>
                    <span class="log-message">{{ log.message }}</span>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </section>
      </div>
    </main>

    <!-- 统一页脚组件 -->
    <AppFooter />
  </div>
</template>

<script setup lang="ts">
// ==================== 导入依赖 ====================

// Vue 3 组合式 API
import { ref, reactive, onMounted } from 'vue'

// Element Plus 组件
import { ElMessage, ElMessageBox } from 'element-plus'

// 自定义组件导入
import AppHeader from '../components/AppHeader.vue'  // 统一导航栏组件
import AppFooter from '../components/AppFooter.vue'  // 统一页脚组件

// HTTP请求拦截器
import { httpGet, httpPost, httpPut, httpDelete, httpRequest } from '../utils/httpInterceptor'

// ==================== 响应式数据 ====================

// 加载状态管理
const loadingStates = reactive({
  get: false,
  post: false,
  put: false,
  delete: false,
  networkError: false,
  authError: false,
  serverError: false,
  retry: false,
  timeout: false,
  custom: false
})

// 请求配置
const requestConfig = reactive({
  url: '/api/test',
  method: 'GET',
  data: '{"name": "test", "value": 123}',
  showLoading: true,
  showError: true,
  retryCount: 3
})

// 响应数据
const responseData = ref('')
const errorData = ref('')
const activeTab = ref('response')

// 请求日志
const requestLogs = ref<Array<{
  time: string
  message: string
  type: 'info' | 'success' | 'error' | 'warning'
}>>([])

// ==================== 工具函数 ====================

/**
 * 添加日志记录
 * @param message 日志消息
 * @param type 日志类型
 */
const addLog = (message: string, type: 'info' | 'success' | 'error' | 'warning' = 'info'): void => {
  const now = new Date()
  const time = now.toLocaleTimeString()
  
  requestLogs.value.unshift({
    time,
    message,
    type
  })
  
  // 限制日志数量
  if (requestLogs.value.length > 50) {
    requestLogs.value = requestLogs.value.slice(0, 50)
  }
}

/**
 * 清空响应数据
 */
const clearResponse = (): void => {
  responseData.value = ''
  errorData.value = ''
}

/**
 * 处理请求响应
 * @param response 响应数据
 */
const handleResponse = (response: any): void => {
  responseData.value = JSON.stringify(response, null, 2)
  errorData.value = ''
  activeTab.value = 'response'
  addLog('请求成功', 'success')
}

/**
 * 处理请求错误
 * @param error 错误信息
 */
const handleError = (error: any): void => {
  errorData.value = JSON.stringify(error, null, 2)
  responseData.value = ''
  activeTab.value = 'error'
  addLog(`请求失败: ${error.message}`, 'error')
}

// ==================== 测试函数 ====================

/**
 * 测试GET请求
 * @description 演示基础的GET请求功能
 */
const testGetRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.get = true
  addLog('开始GET请求测试', 'info')
  
  try {
    const response = await httpGet('/api/users', { page: 1, limit: 10 })
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.get = false
  }
}

/**
 * 测试POST请求
 * @description 演示基础的POST请求功能
 */
const testPostRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.post = true
  addLog('开始POST请求测试', 'info')
  
  try {
    const response = await httpPost('/api/users', {
      name: '测试用户',
      email: 'test@example.com',
      age: 25
    })
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.post = false
  }
}

/**
 * 测试PUT请求
 * @description 演示基础的PUT请求功能
 */
const testPutRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.put = true
  addLog('开始PUT请求测试', 'info')
  
  try {
    const response = await httpPut('/api/users/1', {
      name: '更新用户',
      email: 'updated@example.com',
      age: 30
    })
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.put = false
  }
}

/**
 * 测试DELETE请求
 * @description 演示基础的DELETE请求功能
 */
const testDeleteRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.delete = true
  addLog('开始DELETE请求测试', 'info')
  
  try {
    const response = await httpDelete('/api/users/1')
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.delete = false
  }
}

/**
 * 测试网络错误
 * @description 演示网络错误的处理
 */
const testNetworkError = async (): Promise<void> => {
  clearResponse()
  loadingStates.networkError = true
  addLog('开始网络错误测试', 'warning')
  
  try {
    const response = await httpGet('/api/nonexistent-endpoint')
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.networkError = false
  }
}

/**
 * 测试认证错误
 * @description 演示认证错误的处理
 */
const testAuthError = async (): Promise<void> => {
  clearResponse()
  loadingStates.authError = true
  addLog('开始认证错误测试', 'warning')
  
  try {
    const response = await httpGet('/api/protected-resource')
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.authError = false
  }
}

/**
 * 测试服务器错误
 * @description 演示服务器错误的处理
 */
const testServerError = async (): Promise<void> => {
  clearResponse()
  loadingStates.serverError = true
  addLog('开始服务器错误测试', 'warning')
  
  try {
    const response = await httpGet('/api/server-error')
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.serverError = false
  }
}

/**
 * 测试重试机制
 * @description 演示请求重试功能
 */
const testRetryMechanism = async (): Promise<void> => {
  clearResponse()
  loadingStates.retry = true
  addLog('开始重试机制测试', 'info')
  
  try {
    const response = await httpGet('/api/unstable-endpoint', {}, {
      retryCount: 3,
      retryDelay: 1000
    })
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.retry = false
  }
}

/**
 * 测试超时请求
 * @description 演示请求超时的处理
 */
const testTimeoutRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.timeout = true
  addLog('开始超时请求测试', 'warning')
  
  try {
    const response = await httpGet('/api/slow-endpoint', {}, {
      timeout: 2000
    })
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.timeout = false
  }
}

/**
 * 测试自定义请求
 * @description 演示自定义配置的请求
 */
const testCustomRequest = async (): Promise<void> => {
  clearResponse()
  loadingStates.custom = true
  addLog('开始自定义请求测试', 'info')
  
  try {
    let data = null
    if (requestConfig.data) {
      try {
        data = JSON.parse(requestConfig.data)
      } catch (e) {
        ElMessage.error('请求数据格式错误，请检查JSON格式')
        loadingStates.custom = false
        return
      }
    }
    
    const response = await httpRequest({
      url: requestConfig.url,
      method: requestConfig.method as any,
      data,
      showLoading: requestConfig.showLoading,
      showError: requestConfig.showError,
      retryCount: requestConfig.retryCount
    })
    
    handleResponse(response)
  } catch (error) {
    handleError(error)
  } finally {
    loadingStates.custom = false
  }
}

// ==================== 生命周期钩子 ====================

onMounted(() => {
  addLog('HTTP请求拦截器演示页面已加载', 'success')
})
</script>

<style scoped lang="scss">
// 导入样式
@use '../assets/styles/clients/_http-interceptor-demo';
</style>
